package cn.cttic.app.service.impl;

import cn.cttic.order.api.domain.BaseSaleOrder;
import cn.cttic.order.api.domain.bo.BaseSaleOrderBo;
import cn.cttic.order.api.domain.vo.BaseSaleOrderVo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.cttic.app.api.domain.bo.SaleOrderQueryBo;
import cn.cttic.common.core.utils.StringUtils;
import cn.cttic.common.mybatis.core.page.PageQuery;
import cn.cttic.common.mybatis.core.page.TableDataInfo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import cn.cttic.app.mapper.BaseSaleOrderMapper;
import cn.cttic.app.service.IBaseSaleOrderService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 销售订单Service业务层处理
 *
 * @author Times.Studio
 * @date 2024-05-23
 */
@RequiredArgsConstructor
@Service
public class BaseSaleOrderServiceImpl implements IBaseSaleOrderService {

    private final BaseSaleOrderMapper baseMapper;

    /**
     * 查询销售订单
     */
    @Override
    public BaseSaleOrderVo queryById(String id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询销售订单列表
     */
    @Override
    public TableDataInfo<BaseSaleOrderVo> queryPageList(BaseSaleOrderBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BaseSaleOrder> lqw = buildQueryWrapper(bo);
        Page<BaseSaleOrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询销售订单列表
     */
    @Override
    public TableDataInfo<BaseSaleOrderVo> searchPageList(SaleOrderQueryBo bo, String userId) {
        QueryWrapper lqw = buildQueryWrapper(bo, userId);
        Page<BaseSaleOrderVo> result = baseMapper.searchPageList(bo.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询销售订单列表
     */
    @Override
    public List<BaseSaleOrderVo> queryList(BaseSaleOrderBo bo) {
        LambdaQueryWrapper<BaseSaleOrder> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private QueryWrapper buildQueryWrapper(SaleOrderQueryBo bo, String userId) {
        QueryWrapper<BaseSaleOrder> qw = new QueryWrapper();
        if (StringUtils.isNotBlank(bo.getQueryParam())) {
            qw.and(iqw ->
                iqw.like("saleOrder.last_name", bo.getQueryParam())
                    .or()
                    .like("saleOrder.id", bo.getQueryParam())
                    .or()
                    .like("saleOrder.phone", bo.getQueryParam())
                    .or()
                    .like("product.product_name", bo.getQueryParam())
                    .or()
                    .like("device.device_name", bo.getQueryParam())
                    .or()
                    .like("device.device_model", bo.getQueryParam())
            );
        }
        qw.eq("saleOrder.sales_man_id", userId);
        qw.ge(ObjectUtil.isNotNull(bo.getDelayDays()), "TIMESTAMPDIFF(DAY,saleOrder.create_time,NOW())", bo.getDelayDays());
        qw.eq(ObjectUtil.isNotNull(bo.getOrderStatus()), "saleOrder.`status`", bo.getOrderStatus());
        qw.orderByDesc("saleOrder.create_time");
        return qw;
    }

    private LambdaQueryWrapper<BaseSaleOrder> buildQueryWrapper(BaseSaleOrderBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BaseSaleOrder> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getLastName()), BaseSaleOrder::getLastName, bo.getLastName());
        lqw.like(StringUtils.isNotBlank(bo.getFirstName()), BaseSaleOrder::getFirstName, bo.getFirstName());
        lqw.eq(bo.getGender() != null, BaseSaleOrder::getGender, bo.getGender());
        lqw.like(StringUtils.isNotBlank(bo.getPhone()), BaseSaleOrder::getPhone, bo.getPhone());
        lqw.like(StringUtils.isNotBlank(bo.getCarNo()), BaseSaleOrder::getCarNo, bo.getCarNo());
        lqw.eq(StringUtils.isNotBlank(bo.getProductId()), BaseSaleOrder::getProductId, bo.getProductId());
        lqw.eq(StringUtils.isNotBlank(bo.getSalesManId()), BaseSaleOrder::getSalesManId, bo.getSalesManId());
        lqw.eq(bo.getStatus() != null, BaseSaleOrder::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增销售订单
     */
    @Override
    public Boolean insertByBo(BaseSaleOrderBo bo) {
        BaseSaleOrder add = BeanUtil.toBean(bo, BaseSaleOrder.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改销售订单
     */
    @Override
    public Boolean updateByBo(BaseSaleOrderBo bo) {
        BaseSaleOrder update = BeanUtil.toBean(bo, BaseSaleOrder.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BaseSaleOrder entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除销售订单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
